﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using Telerik.Web.UI;
using System.Web.Script.Services;

public partial class Components_Member_ListRole : System.Web.UI.UserControl
{
    //DatabaseHelper DB = new DatabaseHelper();
    //DataTable dt = new DataTable();
   // int DetailID = 21;
    string DetailName = "Role";
    DBDataContext dtx = LINQUtil.GetDBWriteOnly();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SetupForm();
        }
    }

    protected void SetupForm()
    {
        //Load dữ liệu cho các control khi vừa load form
        Utils.LoadDataToCombo(cboParentID, "Role_cbo_ParentID",DbType.Int32, 1);
        cboParentID.SelectedIndex = 0;

        //Hiển thị thông tin các column trên lưới khi load form, lúc này chưa cần load dữ liệu lên lưới
        grvData.DataSource = new DataTable();
        grvData.DataBind();
        //btnSearch_Click(null, null);
    }

    protected void ClearForm()
    {
        cboParentID.SelectedIndex = 0;
        txtRoleName.Text = "";
        DataTable dt = new DataTable();
        grvData.DataSource = dt;
        grvData.DataBind();
    }

    private void LoadDatatoGrid()
    {
        try
        {
            //DB.ClearParameter();

            //DbParameter paramRoleName = DB.Parameter;
            //paramRoleName.ParameterName = "RoleName";
            //paramRoleName.DbType = DbType.String;
            //paramRoleName.Value = cboParentID.SelectedIndex>0?cboParentID.Text:"";
            //DB.AddParameter(paramRoleName);

            //DbParameter paramParentID = DB.Parameter;
            //paramParentID.ParameterName = "ParentID";
            //paramParentID.DbType = DbType.String;
            //paramParentID.Value = -1;// cboParentID.SelectedValue;
            //DB.AddParameter(paramParentID);

            //DbParameter paramRemark = DB.Parameter;
            //paramRemark.ParameterName = "Remark";
            //paramRemark.DbType = DbType.String;
            //paramRemark.Value = "";
            //DB.AddParameter(paramRemark);

            //DbParameter paramIsSystemRole = DB.Parameter;
            //paramIsSystemRole.ParameterName = "IsSystemRole";
            //paramIsSystemRole.DbType = DbType.Int32;
            //paramIsSystemRole.Value = -1;
            //DB.AddParameter(paramIsSystemRole);

            //dt = DB.ExecuteDataTable("Role_Search", CommandType.StoredProcedure, ConnectionState.CloseOnExit);


            DBDataContext dtx = LINQUtil.GetDBReadOnly();
            List<Role_SearchResult> listResult = dtx.Role_Search(txtRoleName.Text, cboParentID.SelectedValue == "" ? -1 : int.Parse(cboParentID.SelectedValue), "", -1).ToList();
            lblResult.Text = "";
            this.grvData.DataSource = listResult;
            this.grvData.DataBind();
            this.grvData.Visible = true;
           
        }
        catch (Exception ex)
        {

            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;

        }
    }

    

    protected void grvData_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadDatatoGrid();
    }

    protected void grvData_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
       
            string commandName = e.CommandName;
            if (commandName == "ViewItem" || commandName == "EditDelItem")
            {
                int iRow = e.Item.ItemIndex;
                if (commandName == "ViewItem")
                {
                    Session["Role_ID"] = grvData.Items[iRow]["ID"].Text.Replace("&nbsp;", ""); //Lấy giá trị ID
                    Session[DetailName] = 2;
                    RadWindow2.NavigateUrl = "RoleList.aspx";
                    RadWindow2.ID = "Rad1";
                    RadWindow2.VisibleOnPageLoad = true;
                    RadWindow2.Width = 1000;
                    RadWindow2.Height = 500;
                    RadWindow2.VisibleStatusbar = false;
                    RadWindowManager1.Windows.Clear();
                    RadWindowManager1.Windows.Add(RadWindow2);
                    //ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "window.open( 'ViewDetail.aspx?ID=" + DetailID + "', null, 'height=400,width=800,status=yes,toolbar=no,menubar=no,location=no' );", true);
                    // ModalPopupExtender.Show();
                }
                else if (commandName == "EditDelItem")
                {
                    Session["Role_ID"] = grvData.Items[iRow]["ID"].Text.Replace("&nbsp;", ""); //Lấy giá trị ID
                    Session[DetailName] = 1; //0: tạo mới; 1: Sửa/Xóa; 2: Chỉ xem
                    Response.Redirect("~/Role");
                }
            }
       
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
       
        try
        {
            LoadDatatoGrid();
            btnClear.Focus();
        }
        catch (Exception ex)
        {

            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;

        }
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        
        Session[DetailName] = 0; //0: tạo mới; 1: Sửa/Xóa; 2: Chỉ xem
        Response.Redirect("~/Role");
        btnDelete.Focus();
    }
    protected void btnClear_Click1(object sender, EventArgs e)
    {
       
        ClearForm();
        btnNew.Focus();
    }
    protected void btnDelSelection_Click(object sender, EventArgs e)
    {
        
       bool isDelete = false;
        foreach (GridDataItem grdItem in grvData.Items)
        {
            CheckBox chkSelection = (CheckBox)grdItem["checkbox"].Controls[0];
            if (chkSelection.Checked == true)
            {
                int roleID =Convert.ToInt32(grdItem.Cells[3].Text);
                //DBDataContext dtr = LINQUtil.GetDBReadOnly();
                //var roleaction = (from p in dtr.RoleActions
                //            where p.RoleID == roleID && p.Status == 'A'
                //            select p).FirstOrDefault();
                //var roleFunction = (from p in dtr.RoleFunctions
                //                  where p.RoleID == roleID 
                //                  select p).FirstOrDefault();
                //var roleStep = (from p in dtr.RoleSteps
                //                    where p.RoleID == roleID && p.Status == 'A'
                //                    select p).FirstOrDefault();
                //var userRole = (from p in dtr.UserRoles
                //                    where p.RoleID == roleID 
                //                    select p).FirstOrDefault();
                //if (roleaction != null || roleFunction != null || roleStep != null || userRole != null)
                //{
                //    String jsScript = "";
                //    jsScript += "var answer=confirm(\'Nhóm quyền này đang được sử dụng để phân quyền cho các user. Nhấn OK để xoá các phân quyền liên quan đến Nhóm quyền này.\');\n";

                //    jsScript += "if (answer){\n";
                //    jsScript += "DelRole(" + roleID + ");\n";

                //    jsScript += "}\n"; 
                //    jsScript += "else{\n";//cancel
                //    jsScript += ";\n";   //Or don't do anything

                //    jsScript += "}\n";
                //    ScriptManager.RegisterStartupScript(u, Page.GetType(), "", jsScript, true);
                //    //ScriptManager.RegisterStartupScript(u, Page.GetType(), "script", jsScript, true);
                //    //JavascriptUtil.LoadMessage(u,false,"Nhóm quyền này đang được sử dụng không thể xoá.");
                //    //string cls ="msgSuccess";
                //   // ScriptManager.RegisterStartupScript(u, u.GetType(), "script", "AjaxPanelResponseMessage('" + jsScript + "','');", true);
                //    LoadDatatoGrid();
                //    grvData.Rebind();
                //    return;
                //}
                //else
                //{
                    isDelete = true;
                    //DeleteData(roleID);
                    DelAllRole(roleID);
                    
                //}
                
            }
        }
        if (isDelete)
        {
            JavascriptUtil.LoadMessage(u, true, "Xoá thành công!");
            LoadDatatoGrid();
        }
        else
        {
            JavascriptUtil.LoadMessage(u, false, "Cần chọn dòng để xoá");
        }
        grvData.Rebind();
    }
        
    //[System.Web.Services.WebMethod]

    void DelAllRole(int ID)
    {
        dtx.Role_DeleteALL(ID, Session["UserName"].ToString());
    }

    protected void DeleteData(int ID)
    {
        //DB.ClearParameter();

        ////Add param cho store
        //DbParameter paramCMCode = DB.Parameter;
        //paramCMCode.ParameterName = "ID";
        //paramCMCode.DbType = DbType.Int32;
        //paramCMCode.Value = ID;
        //DB.AddParameter(paramCMCode);

        //DbParameter paramByUser = DB.Parameter;
        //paramByUser.ParameterName = "ByUser";
        //paramByUser.DbType = DbType.String;
        //paramByUser.Value = Session["UserName"].ToString(); //User đang thao tác
        //DB.AddParameter(paramByUser);

        try
        {
            
            dtx.Role_Delete(ID, Session["UserName"].ToString());
            //var
            //dt = DB.ExecuteDataTable("Role_Delete", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
        }
        catch (Exception ex)
        {
            lblResult.Text = "";
            lblResult.Text = "Thông báo lỗi: Xóa không thành công. Mã lỗi: Role - " + ex.Message;
        }
    }
    protected void grvData_PageIndexChanged1(object sender, GridPageChangedEventArgs e)
    {
        LoadDatatoGrid();
    }
    protected void grvData_PageSizeChanged1(object sender, GridPageSizeChangedEventArgs e)
    {
        LoadDatatoGrid();
    }
    protected void txtRoleName_TextChanged(object sender, EventArgs e)
    {
        btnSearch.Focus();
    }
    protected void cboParentID_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        txtRoleName.Focus();
    }    
}
